import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_patient_record.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/models/patient_record.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/patient_manage/patient_record_add.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 患者病例库
class PatientRecordListPage extends StatefulWidget {
  final Patient patient;

  const PatientRecordListPage({Key key, this.patient}) : super(key: key);

  @override
  _PatientRecordListPageState createState() => _PatientRecordListPageState();
}

class _PatientRecordListPageState extends State<PatientRecordListPage> {
  /// 患者病例列表
  List<PatientRecord> _items = [];

  // 是否有下一页
  int _nextPage = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('病例库'),
        actions: [
          TextButton(
            child: Text(
              '添加病例',
              style: TextStyle(color: Theme.of(context).primaryColor),
            ),
            onPressed: () {
              Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (c) => PatientRecordAddPage(widget.patient)))
                  .then((value) {
                if (value != null && value) {
                  _fetchData();
                }
              });
            },
          )
        ],
      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: _nextPage != 1,
        onRefresh: _fetchData,
        onLoading: _loadMore,
        child: ListView.separated(
            padding: EdgeInsets.symmetric(vertical: 10),
            itemBuilder: (c, i) => ItemPatientRecord(
                  item: _items[i],
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (c) => PatientRecordAddPage(
                          widget.patient,
                          id: _items[i].id,
                        ),
                      ),
                    ).then((value) {
                      if (value != null && value) {
                        _fetchData();
                      }
                    });
                  },
                  onDelete: () => _delete(i),
                ),
            separatorBuilder: (c, i) => CustomDivider(),
            itemCount: _items.length),
      ),
    );
  }

  void _fetchData() async {
    var data = await XHttp.postJson(
        Urls.PATIENT_RECORD_LIST, _buildParams(isRefresh: true));
    _refreshController.refreshCompleted();
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => PatientRecord.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore() async {
    var data = await XHttp.postJson(Urls.PATIENT_RECORD_LIST, _buildParams());
    _refreshController.loadComplete();
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => PatientRecord.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  Map<String, dynamic> _buildParams({bool isRefresh}) {
    if (isRefresh) {
      _nextPage = 1;
    }
    var params = {
      "doctorAccountId": SPUtils.getUser().id, //医生账号id
      "patientAccountId": widget.patient.patiAccountId, //患者账号id
      "pageNo": _nextPage, //页码
      "pageSize": Constants.limit, //每页条数
      "sort": "create_date", //排序字段
      "order": "desc" //排序方式
    };
    return params;
  }

  void _delete(int index) async {
    DialogUtils.showAlertDialog(context, '提示', '确认删除？', onPressed: () async {
      Navigator.pop(context);
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(
        sprintf(Urls.PATIENT_RECORD_DELETE, [_items[index].id]),
      );
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          setState(() {
            _items.removeAt(index);
          });
        }
      }
    });
  }
}
